const redis = require('redis')
const { REDIS_CONF } = require('../conf/db.js')
let { port, host } = REDIS_CONF

//创建实例
const redisClient = redis.createClient(port, host)

//连接redis
!(async function () {
    await redisClient.connect()
        .then(() => {
            console.log('redis is connect success');
        })
        .catch(console.error)
})()

//set操作
async function setSession(key, value) {
    let objVal
    if (typeof value === 'object') {
        objVal = JSON.stringify(value)
    } else objVal = value
    await redisClient.set(key, objVal)
}
//get操作
async function getSession(key) {
    try {
        let val = await redisClient.get(key)
        if (val === null) return val
        try {
            val = JSON.parse(val)
        } catch (err) { }
        return val

    } catch (err) {
        throw err
    }
}

module.exports = {
    setSession,
    getSession

}